<script setup lang="ts">
  import { ref, watch } from 'vue'
  import FinishOrderForm from './FinishOrderForm.vue'
  import { ElMessage } from 'element-plus'

  const props = defineProps<{
    modelValue: boolean
    isBatch: boolean
    orderIds: Array<string>
  }>()

  const emits = defineEmits<{
    (e: 'update:modelValue', value: boolean): void
    (e: 'update'): void
  }>()

  const visible = ref(false)
  const finishOrderFormRef = ref<InstanceType<typeof FinishOrderForm> | null>(null)

  const onClose = () => {
    visible.value = false
    emits('update:modelValue', visible.value)
  }

  const onConfirm = async () => {
    if (finishOrderFormRef.value) {
      const res = await finishOrderFormRef.value.submit(props.orderIds)
      if (res) {
        ElMessage({
          message: res.message,
          type: res.success ? 'success' : 'error',
          plain: true,
          duration: 5000,
          showClose: true,
        })

        if (res.success) {
          onClose()
          finishOrderFormRef.value.reset()
          emits('update')
        }
      }
    }
  }

  watch(
    props,
    (value) => {
      visible.value = value.modelValue
    },
    { immediate: true, deep: true },
  )
</script>

<template>
  <HDialog
    v-model="visible"
    title="确认完成工单"
    :loading="finishOrderFormRef && finishOrderFormRef.submitLoading"
    @close="onClose"
  >
    <div class="finish_order_dialog_form">
      <div v-if="props.orderIds.length > 1" class="tip">
        <span>当前选中&nbsp;</span>
        <span class="num">{{ props.orderIds.length }}</span>
        <span>&nbsp;个工单进行批量操作！</span>
      </div>
      <FinishOrderForm ref="finishOrderFormRef" />
    </div>
    <template #footer>
      <HButton is-modal type="primary" @click="onConfirm">确定</HButton>
      <HButton is-modal @click="onClose">取消</HButton>
    </template>
  </HDialog>
</template>

<style scoped lang="scss">
  .finish_order_dialog_form {
    display: flex;
    flex-direction: column;
    row-gap: 14px;

    .tip {
      .num {
        color: $primaryColor;
      }
    }
  }
</style>
